<template>
  <div>
    <van-sticky>
      <van-nav-bar
          left-arrow
          :title="friendInfo.userNickname"
          @click-left="onClickLeft"
      >
        <template #right>
          <van-image
              round
              width="40px"
              height="40px"
              :src="friendInfo.userHeadImg"
          />
        </template>
      </van-nav-bar>
    </van-sticky>

    <van-pull-refresh v-model="loading" :finished="finished" @refresh="onRefresh" @load="onLoad">
      <div class="content_box" id="box" ref="content">
        <div ref="content_list" v-for="(item, index) in chatList"
             :class="item.position === 'left' ? 'friendBox' : 'meBox'" :key="index">
          <div :class="item.position === 'left' ? 'friendInfo' : 'meInfo'">
            <div style="font-size: 14px">{{ item.nickname }}</div>
            <div :class="item.position === 'left' ? 'friendContentText' : 'meContentText'">
              {{ item.content }}
            </div>
          </div>
          <div>
            <van-image round width="50px" height="50px" :src="item.url"/>
          </div>
        </div>
      </div>
    </van-pull-refresh>
<!--    <van-sticky position="bottom" offset-bottom="0px">-->
      <div class="bottom">
        <van-field
            v-model="message"
            center
            type="textarea"
            :autosize="{ maxHeight: 25, minHeight: 25 }"
            placeholder="输入消息"
            rows="1">
          <template #button>
            <van-button size="small" type="primary" @click="sendOut">发送</van-button>
          </template>
        </van-field>
      </div>
<!--    </van-sticky>-->
  </div>
</template>

<script>
import {router} from "@/router";
import {userInfo} from "@/api/user";
import {sendMessageToUser, getHistoryMessage} from "@/api/message";
import {getSock} from "@/util/socket";
import {Toast} from "vant";
import VConsole from "vconsole"

let vc = new VConsole()
export default {
  name: "chatwindow",
  data() {
    return {
      friendUserId: 0,
      friendInfo: {},
      message: '',
      chatList: [],
      user: {},
      pageIndex: 1,
      pageSize: 20,

      loading: false,
      finished: false
    }
  },
  methods: {
    onClickLeft() {
      history.back()
    },
    onRefresh() {
      this.pageIndex++;
      this.loading = true;
      this.onLoad();
    },
    onLoad() {
      this.getHistoryMessage()
      setTimeout((res) => {
        this.$nextTick(() => {
          this.$refs.content.scrollTop = 0
        })
      }, 100);
      this.loading = false
    },
    getFriendInfo() {
      this.friendUserId = sessionStorage.getItem("friendUserId")
      userInfo(this.friendUserId).then(response => {
        if (response.code === 200) {
          this.friendInfo = response.data
        }
      })
    },
    getHistoryMessage() {
      let requestParam = {
        'sendUserId': this.user.userId,
        'receiveUserId': this.friendUserId,
        'pageIndex': this.pageIndex,
        'pageSize': this.pageSize
      }
      getHistoryMessage(requestParam).then(response => {
        if (response.code === 200) {
          if (response.data.length < 20) {
            this.finished = true
          }
          this.chatList.forEach(item => {
            response.data.push(item)
          })
          this.chatList = response.data;
        }
      })
      this.setPageScrollTo()
    },
    async sendOut() {
      let requestParam = {
        'sendUserId': this.user.userId,
        'receiveUserId': this.friendUserId,
        'sendMessageContent': this.message
      }
      this.chatList.push(
          {
            'url': this.user.userHeadImg,
            'nickname': this.user.userNickname,
            'content': this.message,
            'position': 'right'
          }
      )
      sendMessageToUser(requestParam).then(response => {
        if (response.code !== 200) {
          Toast.fail()
        }
      })
      this.message = ''
      this.setPageScrollTo()
    },
    getChatContent(res) {
      let messageObj = JSON.parse(res)
      this.chatList.push({
        url: messageObj.headImg,
        nickname: messageObj.nickname,
        content: messageObj.message,
        position: 'left',
      })
      this.setPageScrollTo()
    },
    setPageScrollTo() {
      // this.$refs.scrollbarRef.setScrollTop(2000)
      setTimeout((res) => {
        this.$nextTick(() => {
          this.$refs.content.scrollTop = this.$refs.content.scrollHeight;
        })
      }, 100);
    },
  },
  created() {
    if (router.currentRoute.value.params.friendUserId !== undefined) {
      sessionStorage.setItem('friendUserId', router.currentRoute.value.params.friendUserId)
    }
    this.user = JSON.parse(sessionStorage.getItem('user'))
    this.getFriendInfo()
    getSock(this.getChatContent)
    this.getHistoryMessage();
  },
  mounted() {
    this.setPageScrollTo()
  }
}
</script>

<style scoped>
.van-nav-bar {
  --van-nav-bar-background-color: rgb(0, 174, 239);
  --van-nav-bar-icon-color: rgb(0, 0, 0);
  --van-nav-bar-title-text-color: rgb(255, 255, 255);
  --van-nav-bar-height: 60px;
}

.content_box {
  /*
  中间栏计算高度，110是包含了上下固定的两个元素高度90
  这里padding：10px造成的上下够加了10，把盒子撑大了，所以一共是20要减掉
  然后不知道是边框还是组件的原因，导致多出了一些，这里再减去5px刚好。不然会出现滚动条到顶或者底部的时候再滚动的话就会报一个错，或者出现滚动条变长一下的bug
  */
  overflow: auto;
  height: 709px;
  padding: 10px;
}

.timer {
  text-align: center;
  color: #c2c2c2;
}

.meBox {
  width: 100%;
  display: flex;
  margin-bottom: 10px;
}

.meInfo {
  /* 用flex：1把盒子撑开 */
  flex: 1;
  margin-right: 10px;
  /* 用align-items把元素靠右对齐 */
  display: flex;
  flex-direction: column;
  align-items: flex-end;
}

.meContentText {
  background-color: rgb(0, 174, 239);
  /* 把内容部分改为行内块元素，因为盒子flex：1把盒子撑大了，所以用行内块元素让内容宽度不根据父盒子来 */
  /*display: inline-block;*/
  /* 这四句是圆角 */
  border-top-left-radius: 10px;
  border-top-right-radius: 0px;
  border-bottom-right-radius: 10px;
  border-bottom-left-radius: 10px;
  /* 最大宽度限定内容输入到百分61换行 */
  max-width: 61%;
  padding: 5px 10px;
  /* 忽略多余的空白，只保留一个空白 */
  white-space: normal;
  /* 换行显示全部字符 */
  word-break: break-all;
  margin-top: 3px;
  font-size: 14px;
}

.friendBox {
  width: 100%;
  display: flex;
  flex-direction: row-reverse;
  margin-bottom: 10px;
}

.friendInfo {
  /* 用flex：1把盒子撑开 */
  flex: 1;
  margin-left: 10px;
}

.friendContentText {
  background-color: whitesmoke;
  /* 把内容部分改为行内块元素，因为盒子flex：1把盒子撑大了，所以用行内块元素让内容宽度不根据父盒子来 */
  display: inline-block;
  /* 这四句是圆角 */
  border-top-left-radius: 0px;
  border-top-right-radius: 10px;
  border-bottom-right-radius: 10px;
  border-bottom-left-radius: 10px;
  /* 最大宽度限定内容输入到百分61换行 */
  max-width: 61%;
  padding: 5px 10px;
  /* 忽略多余的空白，只保留一个空白 */
  white-space: normal;
  /* 换行显示全部字符 */
  word-break: break-all;
  margin-top: 3px;
  font-size: 14px;
}

.bottom {
  border-top: 1px solid #eaeaea;
  border-bottom: 1px solid #eaeaea;
}
</style>